package com.example.livesettingtest;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import floatWindow2.FloatActionController;
import floatWindow2.FloatPermissionManager;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.btAutoStart)
    Button btAutoStart;

    @BindView(R.id.btLockScreenClear)
    Button btLockScreenClear;

    @BindView(R.id.btWlanNet)
    Button btWlanNet;

    @BindView(R.id.btMultiTasking)
    Button btMultiTasking;

    @BindView(R.id.btNotifySetting)
    Button btNotifySetting;

    @BindView(R.id.btNext)
    Button btNext;

    @BindView(R.id.btPermission)
    Button btPermission;

    String TAG = "MainActivity";
    boolean mIsPermissionFloat = false;
    boolean isBelowAndroid8 = false;  //android7及以下

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setTitle("华为手机");

        //验证华为到底有多少系统列，用于判断手机是否为华为
        String lowerLetterBrand = CommonUtil.getMobileBrandId();  //品牌
        Toast.makeText(this, lowerLetterBrand, Toast.LENGTH_LONG).show();

        //gxw- String strImei = SystemUtil.getIMEI(this);
        if (!lowerLetterBrand.equals(MyConstant.HUAWEI) && !lowerLetterBrand.equals(MyConstant.HUAWEI_HONOR)) {
            finish();
        }
        String mtype = android.os.Build.MODEL; //型号
        Log.i(TAG, "onCreate,mtype=" + mtype);


 /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(getApplicationContext())) {
                //启动Activity让用户授权
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 100);
            }
        }*/
        if(Build.VERSION.SDK_INT < 26) //ANDROID6-7
        {
            btLockScreenClear.setVisibility(View.VISIBLE);
            isBelowAndroid8 = true;
        }
    }

    //以下代码基于HUAWEI 荣耀9 android9
    @OnClick({R.id.btAutoStart, R.id.btWlanNet, R.id.btMultiTasking, R.id.btNotifySetting, R.id.btIgnoreBattery, R.id.btPermission, R.id.btNext,R.id.btLockScreenClear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btAutoStart:      //提示用户关闭自动管理，打开手动管理，华为特有。
                openAutoStart();
                break;
            case R.id.btLockScreenClear:
                lockScreenClear();
                break;
            case R.id.btNotifySetting:  //android标准页面路径，打开通知在后面的btPermission界面也可以打开
                openNotifySetting();
                break;
            case R.id.btIgnoreBattery:  //android标准页面路径
                openIgnorBattery();
                break;
            case R.id.btPermission:         //android标准页面路径
                openPermission(MyConstant.tipType.PERMISSION);
                break;
            case R.id.btWlanNet:
                openWlanSetting();
                break;
            case R.id.btMultiTasking:   //华为特有
                //这个只能做一个说明书
                break;

            case R.id.btNext: //这个按钮目前用于测试实验其他代码
                testSettingAction();
                break;
        }
    }

    /**
     * 锁屏清理
     */
    public void lockScreenClear()
    {
        try {
            ComponentName componentName = null;
            componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity");
            Intent intent = new Intent();
            intent.setComponent(componentName);
            startActivity(intent);
            openFloatWindowTip(MyConstant.tipType.LOCK_SCREEN,mIsPermissionFloat);
        } catch (Exception e) {
          dealErrorSkip(e);
            e.printStackTrace();
        }
        return;
    }

    @Override
    protected void onRestart() {
        Log.i(TAG,"Service MainActivity onRestart");
        super.onRestart();
    }

    @Override
    protected void onPause() {
        Log.i(TAG,"Service MainActivity onPause");
        super.onPause();
    }

    @Override
    protected void onStart() {
        Log.i(TAG,"Service MainActivity onStart");
        super.onStart();
    }

    @Override
    protected void onStop() {
        Log.i(TAG,"Service MainActivity onStop");
        super.onStop();
    }

    @Override
    protected void onResume() {
        Log.i(TAG,"Service MainActivity onResume");
        FloatActionController.getInstance().stopMonkServer(this);
        //gxw:其实这里isPermission返回false时并不代表用户没有打开权限，返回true那绝对是打开了权限。
        mIsPermissionFloat = FloatPermissionManager.getInstance().applyFloatWindow(this);
        super.onResume();
    }

    public void openWlanSetting2() {
        String mtype = android.os.Build.MODEL;  //判断具体型号
        //gxw-   if(mtype.equals("RNE-AL00")) //畅享7S android8.0       STF-AL00华为荣耀9 android8.0.0
        {
            ComponentName componentName = null;
            componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.power.ui.HwPowerManagerActivity");

            Intent intent = new Intent();
            intent.setComponent(componentName);
            int appUid = getApplicationInfo().uid;
            String packageName = this.getPackageName();
            intent.putExtra("app_package", packageName);
            intent.putExtra("app_uid", appUid);

            try {
                startActivity(intent);
            } catch (Exception e) {
                dealErrorSkip(e);
            }
        }
   /* Intent i = new Intent(); WLAN开关
      i.setClassName("com.android.settings", "com.android.settings.Settings$WifiSettingsActivity");
      startActivity(i);*/
    }
    /**
     * 打开WLAN设置，然后点击底部的配置按钮，设置WLAN永不休眠
     */
    private void openWlanSetting() {
        ComponentName componentName = null;
        componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.power.ui.PowerSettingActivity");

        Intent intent = new Intent();
        intent.setComponent(componentName);
        int appUid = getApplicationInfo().uid;
        intent.putExtra("app_uid", appUid);

        try {
            startActivity(intent);
            openFloatWindowTip(MyConstant.tipType.WLAN_ALWAYS,mIsPermissionFloat);
        } catch (Exception e) {

            try {
                openWlanSetting2();   //就近原则，跳转到省电模式（然后点击--更多省电模式--设置WLAN始终连接）
                openFloatWindowTip(MyConstant.tipType.BATTERY_WLAN,mIsPermissionFloat);
            } catch (Exception e1) {
                dealErrorSkip(e1);
                e.printStackTrace();
            }
        }
        return;
    }

    public void dealErrorSkip(Exception e) {
        Log.i(TAG, "跳转异常了");
        Toast.makeText(MainActivity.this, "跳转异常了,errmsg=" + e.getMessage(), Toast.LENGTH_SHORT).show();
        e.printStackTrace();
        Log.i(TAG, e.getMessage());
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        startActivity(intent);
        openFloatWindowTip(MyConstant.tipType.SETTINGS,mIsPermissionFloat);
    }
    /**
     * 打开华为手机管家
     */
    public void openMobileManager() {

        ComponentName componentName = null;
        componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.mainscreen.MainScreenActivity");
        Intent intent = new Intent();
        intent.setComponent(componentName);
        try {
            startActivity(intent);
        } catch (Exception e) {
            dealErrorSkip(e);
        }

    }

    /**
     * 由于设置自启动的方式 各操作系统都不一样，所以需要具体情况返回准确的值
     * @return
     */
    public MyConstant.tipType getTipTypeAutoStart()
    {
        if(isBelowAndroid8)
        {
            return  MyConstant.tipType.AUTO_START7;
        }
        else
        {
            return  MyConstant.tipType.AUTO_START;
        }

    }

    /**
     * 打开自启动设置页面，android 8.0，9.0，7.0都可以打开，只是getTipTypeAutoStart应返回不同的提示
     * 因为各个操作系统都不一样
     *
     *
     */
    private void openAutoStart() {
        ComponentName componentName = null;
        componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");
        Intent intent = new Intent();
        intent.setComponent(componentName);
        try {
            startActivity(intent);
            MyConstant.tipType tipType = getTipTypeAutoStart();
            openFloatWindowTip(tipType,mIsPermissionFloat);

        } catch (Exception e) {

            try {
                openMobileManager();  //如果异常，优先打开手机管家
                openFloatWindowTip(MyConstant.tipType.MOBILE_MANAGER,mIsPermissionFloat);

            } catch (Exception e1) {
                //最坏的情况下，是打开设置页面
                dealErrorSkip(e1);
            }

        }
    }

    /**
     * 打开浮动窗口
     */
    public void openFloatWindowTip(MyConstant.tipType floatWindowType,boolean isPermission) {

        //有对应权限或者系统版本小于7.0
        if (isPermission || Build.VERSION.SDK_INT < 24) {  //gxw:也就是android 6.0以下，这里需要在6.0以下的手机上测试一下
            //开启悬浮窗
            FloatActionController.getInstance().startMonkServer(this,floatWindowType);
        }

        return;
    }


    /**
     * 打开通知设置
     */
    public void openNotifySetting() {

        if(isBelowAndroid8)
        {
            openPermission(MyConstant.tipType.PERMISSION_NOTIFY);
        }
        else
        {
            String packageName = getPackageName();
            int appUid = getApplicationInfo().uid;
            Log.i(TAG, "packageName=" + packageName + ",appUid=" + appUid);
            Intent intent = new Intent();
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");

            //for Android 5-7
            intent.putExtra("app_package", packageName);
            intent.putExtra("app_uid", appUid);

            // for Android O
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName);

            try {
                startActivity(intent);
                openFloatWindowTip(MyConstant.tipType.NOTIFY_SETTING,mIsPermissionFloat);
            } catch (Exception e) {
                dealErrorSkip(e);
            }
        }

        return;
    }


    /**
     * 打开权限
     * * <p>
     * * Input: The Intent's data URI specifies the application package name
     * * to be shown, with the "package" scheme.  That is "package:com.my.app".
     * * <p>
     * * Output: Nothing.
     */

    public void openPermission(MyConstant.tipType tipType) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("package:" + this.getPackageName()));
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        //gxw-intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);打开浮动窗口权限

        try {
            startActivity(intent);
            openFloatWindowTip(tipType,mIsPermissionFloat);
        } catch (Exception e) {
            dealErrorSkip(e);
        }
        return;
    }

    /**
     * 忽略电池优化,即白名单
     */
    public void openIgnorBattery() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
        try {
            startActivity(intent);
            openFloatWindowTip(MyConstant.tipType.IGNORE_BATTERY,mIsPermissionFloat);
        } catch (Exception e) {
            dealErrorSkip(e);
        }
        return;


    }


    private void testSettingAction() {

        try {

            ComponentName componentName = null;
            componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity");
            Intent intent = new Intent();
            intent.setComponent(componentName);
            startActivity(intent);

        } catch (Exception e) {
            Log.i(TAG, "跳转异常了");
            Toast.makeText(MainActivity.this, "跳转异常了", Toast.LENGTH_SHORT).show();
            Log.i(TAG, e.getMessage());
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            e.printStackTrace();
        }

        return;
    }


    /***
     * 这个是根据每一个手机的具体型号来判断的，比较繁琐。
     * @param context
     */

    private void selfStartManagerSettingIntent(Context context) {
        String mtype = android.os.Build.MODEL; // 手机型号STF-AL10  ，这个是我的华为荣耀9
         // 手机型号STF-AL10  ，这个是我的华为荣耀9
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ComponentName componentName = null;
        if (mtype.startsWith("Redmi") || mtype.startsWith("MI")) {
            componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity");
        } else if (mtype.startsWith("HUAWEI")) {
            componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");
        } else if (mtype.startsWith("vivo")) {
            Log.e(TAG, "selfStartManagerSettingIntent: vivo");
            componentName = new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity");
        } else if (mtype.startsWith("ZTE")) {
//            /.autorun.AppAutoRunManager
            componentName = new ComponentName("com.zte.heartyservice", "com.zte.heartyservice.autorun.AppAutoRunManager");
        } else if (mtype.startsWith("F")) {
            Log.e(TAG, "selfStartManagerSettingIntent: F");
            componentName = new ComponentName("com.gionee.softmanager", "com.gionee.softmanager.oneclean.AutoStartMrgActivity");
        } else if (mtype.startsWith("oppo")) {
            componentName = new ComponentName("oppo com.coloros.oppoguardelf", "com.coloros.powermanager.fuelgaue.PowerUsageModelActivity");
        }
        intent.setComponent(componentName);
        try {
            context.startActivity(intent);
        } catch (Exception e) {//抛出异常就直接打开设置页面
            Log.i(TAG, "跳转异常了");
//            intent = new Intent(Settings.ACTION_SETTINGS);
//            context.startActivity(intent);
        }

    }


}
